import React, { useState, useEffect, useCallback } from 'react';
import {
  Table,
  Card,
  Tag,
  Button,
  Space,
  Select,
  DatePicker,
  Input,
  Modal,
  Form,
  message,
  Statistic,
  Row,
  Col,
  Tooltip,
  Badge,
  Avatar,
  Divider,
  Typography,
  Dropdown,
  Menu,
  Switch,
  Progress,
  Spin,
  Alert
} from 'antd';
import ResizableTable from './ResizableTable';
import {
  SearchOutlined,
  FilterOutlined,
  ExportOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  ReloadOutlined,
  DownloadOutlined,
  PrinterOutlined,
  MoreOutlined,
  UserOutlined,
  PhoneOutlined,
  EnvironmentOutlined,
  ClockCircleOutlined,
  DollarOutlined,
  ShoppingCartOutlined,
  TruckOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  RiseOutlined,
  FallOutlined,
  CalendarOutlined,
  SettingOutlined
} from '@ant-design/icons';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, ResponsiveContainer, PieChart, Pie, Cell, BarChart, Bar, Legend } from 'recharts';
import dayjs from 'dayjs';
import api from '../utils/api';
import '../styles/theme.css';
import { getErrorMessage, getSuccessMessage, getHttpErrorMessage, PAGES, ERROR_TYPES, SUCCESS_TYPES } from '../utils/i18n';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
const { Option } = Select;

const ModernOrders = () => {
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(false);
  const [exportLoading, setExportLoading] = useState(false);
  const [statistics, setStatistics] = useState({});
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const [filters, setFilters] = useState({ status: 'all', dateRange: null, searchText: '' });
  const [autoRefresh, setAutoRefresh] = useState(false);
  const [refreshInterval, setRefreshInterval] = useState(30);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [trendData, setTrendData] = useState([]);
  const [categoryData, setCategoryData] = useState([]);
  const [topCustomers, setTopCustomers] = useState([]);
  const [viewMode, setViewMode] = useState('table');
  const [error, setError] = useState(null);

  const COLORS = { primary: '#6366f1', success: '#22c55e', warning: '#f59e0b', error: '#ef4444', info: '#3b82f6', neutral: '#6b7280' };
  const PIE_COLORS = ['#6366f1', '#22c55e', '#f59e0b', '#ef4444', '#8b5cf6', '#06b6d4'];

  const fetchOrders = useCallback(async (page = pagination.current, pageSize = pagination.pageSize, currentFilters = filters) => {
    setLoading(true);
    setError(null);
    try {
      const params = {
        page,
        pageSize,
        status: currentFilters.status === 'all' ? undefined : currentFilters.status,
        startDate: currentFilters.dateRange ? currentFilters.dateRange[0].format('YYYY-MM-DD') : undefined,
        endDate: currentFilters.dateRange ? currentFilters.dateRange[1].format('YYYY-MM-DD') : undefined,
        search: currentFilters.searchText,
      };
      const response = await api.get('/admin/orders', { params });
      setOrders(response.data.orders);
      setPagination(prev => ({ ...prev, total: response.data.total, current: page, pageSize }));
    } catch (error) {
      setError(getErrorMessage('ORDERS', ERROR_TYPES.ORDER_LOAD_FAILED));
      message.error(getErrorMessage('ORDERS', ERROR_TYPES.ORDER_LOAD_FAILED));
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchOrderStatistics = useCallback(async () => {
    try {
        const [statsRes, trendsRes, categoriesRes, customersRes] = await Promise.all([
            api.get('/orders/stats'),
            api.get('/orders/trends'),
            api.get('/orders/categories'),
            api.get('/orders/top-customers'),
        ]);
        setStatistics(statsRes.data);
        setTrendData(trendsRes.data);
        setCategoryData(categoriesRes.data);
        setTopCustomers(customersRes.data);
    } catch (error) {
        setError(getErrorMessage('ORDERS', ERROR_TYPES.ORDER_STATS_LOAD_FAILED));
        message.error(getErrorMessage('ORDERS', ERROR_TYPES.ORDER_STATS_LOAD_FAILED));
    }
}, []);


  useEffect(() => {
    fetchOrders();
    fetchOrderStatistics();
  }, []);

  useEffect(() => {
    let interval;
    if (autoRefresh) {
      interval = setInterval(() => { fetchOrders(); fetchOrderStatistics(); }, refreshInterval * 1000);
    }
    return () => {
      if (interval) clearInterval(interval);
    };
  }, [autoRefresh, refreshInterval]);

  const handleTableChange = (newPagination) => {
    fetchOrders(newPagination.current, newPagination.pageSize, filters);
  };

  const handleFilterChange = (changedFilters) => {
    const newFilters = { ...filters, ...changedFilters };
    setFilters(newFilters);
    fetchOrders(1, pagination.pageSize, newFilters);
  };

  const handleStatusUpdate = async (orderId, newStatus) => {
    try {
      await api.patch(`/orders/${orderId}/status`, { status: newStatus });
      setOrders(prev => prev.map(order => order.id === orderId ? { ...order, status: newStatus } : order));
      message.success(getSuccessMessage(PAGES.ORDERS, SUCCESS_TYPES.STATUS_UPDATE_SUCCESS));
      fetchDashboardData(); // Refresh stats
    } catch (error) {
      message.error(getErrorMessage(PAGES.ORDERS, ERROR_TYPES.STATUS_UPDATE_FAILED));
    }
  };

  const handleBatchOperation = (operation) => {
    Modal.confirm({
      title: `确认${operation}选中的${selectedRowKeys.length}个订单？`,
      onOk: async () => {
        try {
          await api.post('/orders/batch', { orderIds: selectedRowKeys, operation });
          message.success(`批量${operation}成功`);
          setSelectedRowKeys([]);
          fetchOrders();
          fetchDashboardData();
        } catch (error) {
          message.error(`批量${operation}失败`);
        }
      }
    });
  };

  const handleExport = async () => {
    try {
      setExportLoading(true);
      const csvContent = "data:text/csv;charset=utf-8," + 
        "订单ID,客户姓名,订单金额,订单状态,下单时间\n" +
        orders.map(order => 
          `${order.id},${order.customer.name},${order.total},${order.status === 'pending' ? '待处理' : order.status === 'processing' ? '处理中' : order.status === 'completed' ? '已完成' : '已取消'},${dayjs(order.createdAt).format('YYYY-MM-DD HH:mm:ss')}`
        ).join("\n");
      
      const encodedUri = encodeURI(csvContent);
      const link = document.createElement("a");
      link.setAttribute("href", encodedUri);
      link.setAttribute("download", `订单列表_${dayjs().format('YYYY-MM-DD')}.csv`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      message.success(getSuccessMessage('ORDERS', SUCCESS_TYPES.ORDER_EXPORT_SUCCESS));
    } catch (error) {
      message.error(getErrorMessage('ORDERS', ERROR_TYPES.ORDER_EXPORT_FAILED));
    } finally {
      setExportLoading(false);
    }
  };

  const renderStatusTag = (status) => {
    const statusConfig = {
      pending: { color: 'var(--warning-color)', bgColor: 'var(--warning-light)', icon: <ClockCircleOutlined />, text: '待处理' },
      processing: { color: 'var(--info-color)', bgColor: 'var(--info-light)', icon: <ReloadOutlined spin />, text: '处理中' },
      completed: { color: 'var(--success-color)', bgColor: 'var(--success-light)', icon: <CheckCircleOutlined />, text: '已完成' },
      cancelled: { color: 'var(--error-color)', bgColor: 'var(--error-light)', icon: <CloseCircleOutlined />, text: '已取消' }
    };
    const config = statusConfig[status] || statusConfig.pending;
    return (
      <span className="modern-tag" style={{ background: config.bgColor, color: config.color, border: `1px solid ${config.color}` }}>
        {config.icon} {config.text}
      </span>
    );
  };

  const columns = [
    {
        title: '订单信息',
        key: 'orderInfo',
        width: 200,
        render: (_, record) => (
          <div style={{display: 'flex', alignItems: 'center', gap: '10px'}}>
            <Avatar src={record.customer.avatar} icon={<UserOutlined />} size={40} />
            <div>
              <Text strong>{record.id}</Text>
              <br />
              <Text type="secondary">{record.customer.name}</Text>
            </div>
          </div>
        )
      },
      {
        title: '金额',
        dataIndex: 'total',
        key: 'total',
        width: 120,
        sorter: (a, b) => a.total - b.total,
        render: (total) => <Text strong>¥{total.toFixed(2)}</Text>
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 100,
        render: (status) => renderStatusTag(status)
      },
      {
        title: '下单时间',
        dataIndex: 'createdAt',
        key: 'createdAt',
        width: 160,
        render: (createdAt) => dayjs(createdAt).format('YYYY-MM-DD HH:mm')
      },
    {
      title: '操作',
      key: 'actions',
      width: 120,
      render: (_, record) => {
        const menu = (
          <Menu>
            <Menu.Item key="view" icon={<EyeOutlined />}>查看详情</Menu.Item>
            <Menu.Item key="edit" icon={<EditOutlined />}>编辑订单</Menu.Item>
            <Menu.Divider />
            {record.status === 'pending' && <Menu.Item key="complete" icon={<CheckCircleOutlined />} onClick={() => handleStatusUpdate(record.id, 'completed')}>标记完成</Menu.Item>}
            {record.status !== 'cancelled' && <Menu.Item key="cancel" icon={<CloseCircleOutlined />} danger onClick={() => handleStatusUpdate(record.id, 'cancelled')}>取消订单</Menu.Item>}
          </Menu>
        );
        return (
          <Dropdown overlay={menu} trigger={['click']} placement="bottomRight">
            <Button type="text" icon={<MoreOutlined />} />
          </Dropdown>
        );
      }
    }
  ];

  if (error) return <Alert message={getErrorMessage(PAGES.ORDERS, ERROR_TYPES.ORDER_LOAD_FAILED)} description={error} type="error" showIcon />;

  return (
    <div style={{padding: '24px'}}>
        <Title level={2}>订单管理</Title>
        {loading && <Spin />}
        <Card style={{marginBottom: '24px'}}>
            <Row gutter={16}>
                <Col span={6}><Statistic title="总订单" value={statistics.total} prefix={<ShoppingCartOutlined />} /></Col>
                <Col span={6}><Statistic title="已完成" value={statistics.completed} prefix={<CheckCircleOutlined />} /></Col>
                <Col span={6}><Statistic title="处理中" value={statistics.processing} prefix={<ClockCircleOutlined />} /></Col>
                <Col span={6}><Statistic title="总收入" value={`¥${(statistics.revenue || 0).toFixed(2)}`} prefix={<DollarOutlined />} /></Col>
            </Row>
        </Card>
        
        <Card>
            <Space style={{marginBottom: 16}}>
                <Input placeholder="搜索订单..." prefix={<SearchOutlined />} onChange={e => handleFilterChange({ searchText: e.target.value })} style={{ width: 200 }} />
                <Select defaultValue="all" style={{ width: 120 }} onChange={value => handleFilterChange({ status: value })}>
                    <Option value="all">所有状态</Option>
                    <Option value="pending">待处理</Option>
                    <Option value="processing">处理中</Option>
                    <Option value="completed">已完成</Option>
                    <Option value="cancelled">已取消</Option>
                </Select>
                <RangePicker onChange={dates => handleFilterChange({ dateRange: dates })} />
                <Button icon={<ExportOutlined />} onClick={handleExport} loading={exportLoading}>导出</Button>
                <Button icon={<ReloadOutlined />} onClick={() => { fetchOrders(); fetchOrderStatistics(); }}>刷新</Button>
            </Space>

            <ResizableTable
                columns={columns}
                dataSource={orders}
                loading={loading}
                pagination={pagination}
                rowKey="id"
                onChange={handleTableChange}
                rowSelection={{ selectedRowKeys, onChange: setSelectedRowKeys }}
            />
        </Card>
    </div>
  );
};

export default ModernOrders;